package com.springframework.boot.common.user.controller;


import com.springframework.boot.common.user.entity.User;
import com.springframework.boot.common.user.service.UserService;
import com.springframework.boot.common.verifyCode.utils.RandomValidateCodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;


@Slf4j
@Controller
@RequestMapping("user")
public class UserController {


    @Autowired
    private UserService userService;



    @GetMapping("index")
    public String index() {
        return "index";
    }


    /**
     * 用户注册
     *
     * @param user
     * @return
     */
    @PostMapping("register")
    public String register(User user) {
        try {
            userService.register(user);
            return "redirect:/login.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            return "redirect:/register.jsp";
        }
    }


    @GetMapping("logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/login.jsp";
    }


    @PostMapping("login")
    public String login(String username, String password, String verifyCode, HttpSession session) {
        //比较验证码
        String code = (String) session.getAttribute(RandomValidateCodeUtil.RANDOMCODEKEY);
        try {
            if (code.equalsIgnoreCase(verifyCode)) {
                Subject subject = SecurityUtils.getSubject();
                subject.login(new UsernamePasswordToken(username, password));
                session.setAttribute("tokenId",String.valueOf(subject.getSession().getId()));
                return "redirect:/index.jsp";

            } else {
                throw new RuntimeException("验证码错误！！！");
            }
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            log.error("用户名错误！！！");
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            log.error("密码错误！！！");
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }

        return "redirect:/login.jsp";
    }
}
